<template>
  <el-link style="float: right" type="primary" @click="handleForgetPassword" :underline="false"
    >{{ t('login.forgetPassword') }}
  </el-link>

  <Dialog :title="t('resetPwd.title')" v-model="resetDialogVisible" width="600" :fullscreen="false">
    <el-form
      ref="resetFormRef"
      :model="resetForm"
      :rules="formRules"
      label-width="120"
      size="small"
    >
      <el-form-item :label="t('resetPwd.username')" prop="username">
        <el-input v-model="resetForm.username" disabled />
      </el-form-item>
      <el-form-item :label="t('resetPwd.password')" prop="password">
        <el-input v-model="resetForm.password" show-password />
      </el-form-item>
      <el-form-item :label="t('resetPwd.code')" prop="code">
        <el-input v-model="resetForm.code" maxlength="6" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="resetLoading" type="primary" @click="submitForm"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="resetDialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

  <Verify
    v-if="showResetVerify"
    ref="resetSmsRef"
    :captchaType="captchaType"
    :imgSize="{ width: '400px', height: '200px' }"
    mode="pop"
    @success="handleSendResetSms"
  />
</template>
<script lang="ts" setup>
import * as LoginApi from '@/api/login'
import { AuthResetPasswordSaveReqVO } from '@/api/login'
import { ElLoading, FormInstance } from 'element-plus'

defineOptions({ name: 'ResetPwd' })

const { t } = useI18n()
const message = useMessage()
const resetLoading = ref(false)
const verify = ref()
const resetSmsRef = ref()
const resetFormRef = ref<FormInstance>()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const resetDialogVisible = ref(false)
const showResetVerify = ref(false)
const resetForm = ref<AuthResetPasswordSaveReqVO>({
  username: '',
  password: '',
  code: ''
})

const formRules = reactive({
  username: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('resetPwd.username'),
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('resetPwd.password'),
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('resetPwd.code'),
      trigger: 'blur'
    }
  ]
})

// step1: 点击重置按钮 弹出输入账号框 输入后滑动验证发送短信
const handleForgetPassword = async () => {
  resetForm.value = {
    username: '',
    password: '',
    code: ''
  }
  try {
    showResetVerify.value = true
    const { value } = await message.prompt(t('resetPwd.inputUsername'), t('resetPwd.title'), {
      closeOnClickModal: false,
      // 4-16位字母和数字
      inputPattern: /^[a-zA-Z0-9]{4,16}$/,
      inputErrorMessage: t('resetPwd.usernameError')
    })
    resetForm.value.username = value
    resetSmsRef.value?.show()
  } catch {
    showResetVerify.value = false
    resetForm.value = {
      username: '',
      password: '',
      code: ''
    }
  }
}

const loading = ref() // ElLoading.service 返回的实例

// step2: 滑动验证后 弹出输入验证码和新密码的窗口
const handleSendResetSms = async (params) => {
  try {
    await ElMessageBox.confirm(t('resetPwd.selectType'), t('resetPwd.selectTitle'), {
      confirmButtonText: t('resetPwd.sms'),
      cancelButtonText: t('resetPwd.mail'),
      type: 'info',
      showClose: false,
      center: true,
      closeOnClickModal: false,
      closeOnPressEscape: false
    } as any)
    // 向手机发送
    loading.value = ElLoading.service({
      lock: true,
      text: t('resetPwd.smsSending'),
      background: 'rgba(0, 0, 0, 0.7)'
    } as any)
    try {
      const res = await LoginApi.sendResetPasswordSmsToUsername({
        username: resetForm.value.username,
        captchaVerification: params.captchaVerification
      })
      if (!res) {
        return
      }
      //
      message.success(t('resetPwd.smsSendTo', { phone: res }))
      resetDialogVisible.value = true
    } finally {
      loading.value?.close()
    }
  } catch {
    // 向邮箱发送
    loading.value = ElLoading.service({
      lock: true,
      text: t('resetPwd.mailSending'),
      background: 'rgba(0, 0, 0, 0.7)'
    } as any)
    try {
      const res = await LoginApi.sendResetPasswordMailToUsername({
        username: resetForm.value.username,
        captchaVerification: params.captchaVerification
      })
      if (!res) {
        return
      }
      //
      message.success(t('resetPwd.mailSendTo', { phone: res }))
      resetDialogVisible.value = true
    } finally {
      loading.value?.close()
    }
  }
}

// step3: 提交新密码和验证码
const submitForm = async () => {
  try {
    // 校验表单
    await resetFormRef.value?.validate()
  } catch {
    return
  }
  // 提交请求
  resetLoading.value = true
  try {
    const response = await LoginApi.resetPassword(resetForm.value)
    if (response) {
      message.success(t('common.updateSuccess'))
      showResetVerify.value = false
      resetDialogVisible.value = false
    } else {
      message.error(t('common.updateError'))
    }
  } finally {
    resetLoading.value = false
  }
}
</script>
